package com.tcm.controller.backend;

import com.tcm.common.enums.ResponseEnum;
import com.tcm.entity.dto.param.LeaderUpdateParam;
import com.tcm.entity.vo.LeaderListResult;
import com.tcm.entity.resp.R;
import com.tcm.exception.DatabaseOperationException;
import com.tcm.service.LeaderService;
import com.tcm.utils.AccessTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * 课程任职管理控制器
 * @author Guqier
 * @version 1.0
 * @date 2023/7/18 16:25
 */
@Slf4j
@RestController
@RequestMapping("/pc/leader")
public class LeaderController {

    @Autowired
    private LeaderService leaderService;

    /**
     * 添加课程组组长关系
     * @param param 课程组组长关系更新参数
     * @param request http请求对象
     * @return 响应结果
     */
    @PostMapping
    public R addLeaderRelationship(@RequestBody @Valid LeaderUpdateParam param, HttpServletRequest request){
        boolean b = false;
        try {
            b = leaderService.addLeaderRelationship(param, AccessTokenUtil.getUserId(request));
        } catch (DatabaseOperationException e) {
            return R.fail(0, e.getMessage());
        }
        return b ? R.success() : R.fail(ResponseEnum.PARAM_IS_INVAlID);
    }

    /**
     * 删除课程组组长关系
     * @param id 课程组组长关系ID
     * @param request http请求对象
     * @return 响应结果
     */
    @DeleteMapping
    public R removeLeaderRelationship(@RequestParam Long id, HttpServletRequest request){
        boolean b = false;
        try {
            b = leaderService.removeLeaderRelationship(id, AccessTokenUtil.getUserId(request));
        } catch (Exception e) {
            return R.fail(0, e.getMessage());
        }
        return b ? R.success() : R.fail(ResponseEnum.PARAM_IS_INVAlID);
    }

    /**
     * 修改课程组组长关系
     * @param param 课程组组长关系更新参数
     * @param request http请求对象
     * @return 响应结果
     */
    @PutMapping
    public R modifyLeaderRelationship(@RequestBody @Valid LeaderUpdateParam param, HttpServletRequest request){
        if (param.getId() == null) {
            return R.fail(ResponseEnum.PARAM_IS_BLANK);
        }
        boolean b = false;
        try {
            b = leaderService.modifyLeaderRelationship(param, AccessTokenUtil.getUserId(request));
        } catch (Exception e) {
            return R.fail(0, e.getMessage());
        }
        return b ? R.success() : R.fail(ResponseEnum.PARAM_IS_INVAlID);
    }

    /**
     *
     * @param termId
     * @return
     */
    @GetMapping
    public R getLeaderRelationshipList(@RequestParam Long termId){
        List<LeaderListResult> leaderRelationshipList = leaderService.getLeaderRelationshipList(termId);
        return R.success(leaderRelationshipList);
    }

}
